package com.dankegongyu.lib.common.base;

import com.dankegongyu.lib.common.rx.model.IModel;
import com.dankegongyu.lib.common.rx.presenter.RxPresenter;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;

/**
 * @author WuPuquan
 * @version 1.0
 * @since 2017/9/14 15:04
 */

public abstract class BasePresenter<V> extends RxPresenter{

    private WeakReference<V> mView;
    private List<IModel> mModelList = new ArrayList<>();

    public BasePresenter(V view) {
        mView = new WeakReference<>(view);
    }

    @Nullable
    public V getView() {
        if (mView != null) {
            return mView.get();
        }
        return null;
    }

    @Override
    public void addModel(IModel model) {
        if (model != null) {
            mModelList.add(model);
        }
    }

    @Override
    public void onCreate() {
        // 因为Model层是后加的，Model和Presenter都是基于RxLifeCycle的
        // 之前Presenter直接操作网络部分所以网络生命周期是Presenter负责的
        // 现在新的业务或者改动都加入了Model层，所以有Model层的网络生命周期处理交给RxModel
        if (mModelList == null || mModelList.isEmpty()) {
            super.onCreate();
        } else {
            for (IModel model : mModelList) {
                if (model != null) {
                    model.onCreate();
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        if (mModelList == null || mModelList.isEmpty()) {
            super.onDestroy();
        } else {
            for (IModel model : mModelList) {
                if (model != null) {
                    model.onDestroy();
                }
            }
        }

        try {
            if (mView != null) {
                mView.clear();
                mView = null;
            }

            if (mModelList != null) {
                mModelList.clear();
                mModelList = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
